﻿using Biz.Buffer;
using Biz.EF.Platform.SG;
using Hjt212Parser;
using log4net;
using System;
using System.Data.Entity.Validation;
using System.Linq;

namespace Biz.Process
{
    public static class ProcessorData
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ProcessorData));
        /// <summary>
        /// 2011指令处理
        /// 1、处理实时数据
        /// 2、处理分钟数据（无？）
        /// 3、处理小时数据
        /// 4、处理日数据
        /// 5、处理月数据
        /// 6、处理年数据
        /// 7、处理实时监控
        /// 顾浩老总量与严江华总量2011指令区别在表显:
        /// 顾浩用B01-Cou表示表显；严江华用B01-Total表示表显
        /// </summary>
        /// <param name="content"></param>
        public static void Process2011(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }
                try
                {
                    var master = new 主实时数据
                    {
                        企业基本信息ID = letport.企业基本信息ID,
                        企业排口ID = letport.ID,
                        监测时间 = datatime.Value,
                        RTD = Parser.GetDoubleByKey("B01-Rtd", content) ?? 0,
                        累计量 =
                            Parser.GetDecimalByKey("B01-Cou", content) ?? Parser.GetDecimalByKey("B01-Total", content) ?? 0,
                        污染物类别ID =
                            CommonInformation.GetContamType("B01") == null
                                ? 2
                                : CommonInformation.GetContamType("B01").ID
                    };
                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        if (!code.Contains("B01"))
                        {
                            var detail = new 从实时数据
                            {
                                RTD = Parser.GetDoubleByKey(code + "-Rtd", content) ?? 0,
                                污染物编码ID =
                                    CommonInformation.GetContamCode(code) == null
                                        ? 2
                                        : CommonInformation.GetContamCode(code).ID
                            };
                            master.从实时数据.Add(detail);
                        }
                    }
                    pCtx.主实时数据.Add(master);
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }
        //public static void ProcessMinuteData(string content)
        //{
        //    using (var pCtx = new PlatformXpfContext())
        //    {
        //        var mn = Parser.GetStringByKey("MN", content);
        //        if (string.IsNullOrEmpty(mn))
        //        {
        //            return;
        //        }

        //        var datatime = Parser.GetDateTimeByKey("DataTime", content);
        //        if (!datatime.HasValue)
        //        {
        //            return;
        //        }

        //        var letport = CommonInformation.GetLetportByMn(mn);
        //        if (letport == null)
        //        {
        //            return;
        //        }

        //        try
        //        {
        //            var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day,
        //                datatime.Value.Hour, datatime.Value.Minute / 10 * 10,
        //                0);
        //            var end = begin.AddMinutes(10);
        //            var master = pCtx.主分钟数据
        //                .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
        //                .Where(t => t.企业排口ID == letport.ID)
        //                .Where(t => t.监测时间 >= begin)
        //                .FirstOrDefault(t => t.监测时间 < end);

        //            if (master == null)
        //            {
        //                master = new 主分钟数据
        //                {
        //                    企业基本信息ID = letport.企业基本信息ID,
        //                    企业排口ID = letport.ID,
        //                    监测时间 = datatime.Value,
        //                    时段量 = Parser.GetDoubleByKey("B01-Cou", content) ?? 0,
        //                    污染物类别ID =
        //                        CommonInformation.GetContamType("B01") == null
        //                            ? 2
        //                            : CommonInformation.GetContamType("B01").ID
        //                };
        //                pCtx.主分钟数据.Add(master);
        //            }
        //            master.监测时间 = datatime.Value;
        //            master.时段量 = Parser.GetDoubleByKey("B01-Cou", content) ?? 0;

        //            var codes = Parser.GetPollutantCodes(content);
        //            foreach (var code in codes)
        //            {
        //                var contamCodeId = CommonInformation.GetContamCode(code) == null
        //                    ? 2
        //                    : CommonInformation.GetContamCode(code).ID;
        //                if (!code.Contains("B01"))
        //                {
        //                    var detail = master.从分钟数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
        //                    if (detail == null)
        //                    {
        //                        detail = new 从分钟数据
        //                        {
        //                            Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0,
        //                            污染物编码ID =
        //                                CommonInformation.GetContamCode(code) == null
        //                                    ? 2
        //                                    : CommonInformation.GetContamCode(code).ID,
        //                            Avg = Parser.GetDoubleByKey(code + "-Avg", content)
        //                        };
        //                        master.从分钟数据.Add(detail);
        //                    }
        //                    detail.Avg = Parser.GetDoubleByKey(code + "-Rtd", content) ?? 0;
        //                    detail.Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0;
        //                }
        //            }
        //            pCtx.SaveChanges();
        //        }
        //        catch (Exception ex)
        //        {
        //            Log.Error(ex);
        //        }
        //    }
        //}
        /// <summary>
        /// 顾浩老总量在2011指令中用Code-Day表示日数据
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessDayDataFrom2011(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day,
                        0, 0, 0);
                    var end = begin.AddDays(1);
                    var master = pCtx.主日数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);

                    double? cou
                        = Parser.GetDoubleByKey("B01-Day", content);
                    if (master == null)
                    {
                        master = new 主日数据
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            监测时间 = datatime.Value,
                            时段量 = cou ?? 0,
                            污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                        };
                        pCtx.主日数据.Add(master);
                    }
                    master.监测时间 = datatime.Value;
                    master.时段量 = cou ?? 0;
                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从日数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从日数据
                                {
                                    Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从日数据.Add(detail);
                            }
                            detail.Avg = Parser.GetDoubleByKey(code + "-Rtd", content) ?? 0;
                            detail.Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0;
                        }
                    }
                    pCtx.SaveChanges();

                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }
        /// <summary>
        /// 顾浩老总量在2011指令中用Code-Mon表示月数据
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessMonthDataFrom2011(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, 1,
                        0, 0, 0);
                    var end = begin.AddMonths(1);
                    var master = pCtx.主月数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);
                    double? cou
                        = Parser.GetDoubleByKey("B01-Mon", content);
                    if (master == null)
                    {
                        master = new 主月数据
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            监测时间 = datatime.Value,
                            时段量 = cou ?? 0,
                            污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                        };
                        pCtx.主月数据.Add(master);
                    }
                    master.监测时间 = datatime.Value;
                    master.时段量 = cou ?? 0;
                    //todo:因子没有从实时数据表取平均等
                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从月数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从月数据
                                {
                                    Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从月数据.Add(detail);
                            }
                            detail.Avg = Parser.GetDoubleByKey(code + "-Rtd", content) ?? 0;
                            detail.Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0;
                        }
                    }
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }

            }
        }
        /// <summary>
        /// 严江华总量2061指令,顾浩老总量没有
        /// </summary>
        /// <param name="content"></param>
        public static bool Process2061(string content)
        {

            using (var pCtx = new PlatformXpfContext())
            {

                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return false;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return false;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return false;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day,
                        datatime.Value.Hour, 0, 0);
                    var end = begin.AddHours(1);
                    var master = pCtx.主小时数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);

                    double? hourCou
                        = Parser.GetDoubleByKey("B01-Cou", content);

                    if (master != null)
                    {
                        return false;
                    }

                    master = new 主小时数据
                    {
                        企业基本信息ID = letport.企业基本信息ID,
                        企业排口ID = letport.ID,
                        监测时间 = datatime.Value,
                        时段量 = hourCou ?? 0,
                        污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                    };
                    pCtx.主小时数据.Add(master);

                    master.监测时间 = datatime.Value;
                    master.时段量 = hourCou ?? 0;

                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从小时数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从小时数据
                                {
                                    Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从小时数据.Add(detail);
                            }
                            detail.Avg = Parser.GetDoubleByKey(code + "-Avg", content) ?? 0;
                            detail.Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0;
                        }
                    }
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }

                return true;
            }
        }
        /// <summary>
        /// 通过2061指令计算当日排放量，专为严江华总量
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessDayDataBySumHour(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, 0, 0, 0);
                    var end = begin.AddDays(1);
                    //被累加项
                    var accumulatedItems = pCtx.主小时数据.Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin).ToList();

                    var master = pCtx.主日数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);

                    if (master == null)
                    {
                        master = new 主日数据
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            监测时间 = datatime.Value,
                            时段量 = 0,
                            污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                        };
                        pCtx.主日数据.Add(master);
                    }

                    master.监测时间 = datatime.Value;
                    master.时段量 = accumulatedItems.Sum(t => t.时段量) ?? 0;

                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从日数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从日数据
                                {
                                    Cou = 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从日数据.Add(detail);
                            }

                            detail.Cou = 0;
                            detail.Avg = 0;
                            var count = 0;
                            foreach (var month in accumulatedItems)
                            {
                                var item = month.从小时数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                                if (item != null)
                                {
                                    detail.Cou += item.Cou;
                                    detail.Avg += item.Avg;
                                    count++;
                                }
                            }
                            if (count > 0)
                            {
                                detail.Avg = detail.Avg / count;
                            }
                        }
                    }
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }
        /// <summary>
        /// 严江华总量2031指令,顾浩老总量没有
        /// </summary>
        /// <param name="content"></param>
        public static bool Process2031(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return false;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return false;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return false;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day,
                        0, 0, 0);
                    var end = begin.AddDays(1);
                    var master = pCtx.主日数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);

                    double? hourCou
                        = Parser.GetDoubleByKey("B01-Cou", content);

                    if (master == null)
                    {
                        master = new 主日数据
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            监测时间 = datatime.Value,
                            时段量 = hourCou ?? 0,
                            污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                        };
                        pCtx.主日数据.Add(master);
                    }

                    master.监测时间 = datatime.Value;
                    master.时段量 = hourCou ?? 0;
                    //todo:因子没有从实时数据表取平均等
                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从日数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从日数据
                                {
                                    Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从日数据.Add(detail);
                            }

                            detail.Avg = Parser.GetDoubleByKey(code + "-Avg", content) ?? 0;
                            detail.Cou = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0;
                        }
                    }

                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                 Log.Error(ex);
                    
                }

                return true;
            }
        }
        /// <summary>
        /// 通过2061和2031指令计算当月排放量，专为严江华总量
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessMonthDataBySumDay(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, 1, 0, 0, 0);
                    var end = begin.AddMonths(1);
                    //被累加项
                    var accumulatedItems = pCtx.主日数据.Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin).ToList();

                    var master = pCtx.主月数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);

                    if (master == null)
                    {
                        master = new 主月数据
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            监测时间 = datatime.Value,
                            时段量 = 0,
                            污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                        };
                        pCtx.主月数据.Add(master);
                    }

                    master.监测时间 = datatime.Value;
                    master.时段量 = accumulatedItems.Sum(t => t.时段量) ?? 0;

                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从月数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从月数据
                                {
                                    Cou = 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从月数据.Add(detail);
                            }
                            detail.Cou = 0;
                            detail.Avg = 0;
                            var count = 0;
                            foreach (var month in accumulatedItems)
                            {
                                var item = month.从日数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                                if (item != null)
                                {
                                    detail.Cou += item.Cou;
                                    detail.Avg += item.Avg;
                                    count++;
                                }
                            }
                            if (count > 0)
                            {
                                detail.Avg = detail.Avg / count;
                            }
                        }
                    }
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }
        /// <summary>
        /// 根据月计算年排放量，顾浩总量和严江华总量都用
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessYearDataBySumMonth(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }

                try
                {
                    var begin = new DateTime(datatime.Value.Year, 1, 1, 0, 0, 0);
                    var end = begin.AddYears(1);
                    //被累加项
                    var accumulatedItems = pCtx.主月数据.Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin).ToList();

                    var master = pCtx.主年数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= begin)
                        .FirstOrDefault(t => t.监测时间 < end);

                    if (master == null)
                    {
                        master = new 主年数据
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            监测时间 = datatime.Value,
                            时段量 = 0,
                            污染物类别ID =
                                CommonInformation.GetContamType("B01") == null
                                    ? 2
                                    : CommonInformation.GetContamType("B01").ID
                        };
                        pCtx.主年数据.Add(master);
                    }

                    master.监测时间 = datatime.Value;
                    master.时段量 = accumulatedItems.Sum(t => t.时段量) ?? 0;

                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var detail = master.从年数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail == null)
                            {
                                detail = new 从年数据
                                {
                                    Cou = 0,
                                    污染物编码ID =
                                        CommonInformation.GetContamCode(code) == null
                                            ? 2
                                            : CommonInformation.GetContamCode(code).ID,
                                    Avg = Parser.GetDoubleByKey(code + "-Avg", content)
                                };
                                master.从年数据.Add(detail);
                            }
                            detail.Cou = 0;
                            detail.Avg = 0;
                            var count = 0;
                            foreach (var month in accumulatedItems)
                            {
                                var item = month.从月数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                                if (item != null)
                                {
                                    detail.Cou += item.Cou;
                                    detail.Avg += item.Avg;
                                    count++;
                                }
                            }
                            if (count > 0)
                            {
                                detail.Avg = detail.Avg / count;
                            }
                        }
                    }
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }
        public static void ProcessRealMonitor(string content)
        {
            using (var pCtx = new PlatformXpfContext())
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }

                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null)
                {
                    return;
                }

                try
                {
                    var monitorMaster = pCtx.主实时监控
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID).FirstOrDefault(t => t.企业排口ID == letport.ID);
                    if (monitorMaster == null)
                    {
                        monitorMaster = new 主实时监控
                        {
                            企业基本信息ID = letport.企业基本信息ID,
                            企业排口ID = letport.ID,
                            污染物类别ID = 2
                        };
                        pCtx.主实时监控.Add(monitorMaster);
                    }

                    monitorMaster.实时数据时间 = datatime;
                    monitorMaster.分钟数据时间 = datatime;
                    monitorMaster.瞬时量 = Parser.GetDoubleByKey("B01-Rtd", content) ?? 0;
                    monitorMaster.累计量 = Parser.GetDecimalByKey("B01-Cou", content) ?? Parser.GetDecimalByKey("B01-Total", content) ?? 0;
                    主日数据 dayMaster = null;
                    主月数据 monthMaster = null;
                    if (content.Contains("B01-Day"))
                    {
                        monitorMaster.日排放量 = Parser.GetDoubleByKey("B01-Day", content) ?? 0;
                    }
                    else
                    {
                        var dayBegin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, 0, 0, 0);
                        var dayEnd = dayBegin.AddDays(1);
                        dayMaster = pCtx.主日数据
                            .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                            .Where(t => t.企业排口ID == letport.ID)
                            .Where(t => t.监测时间 >= dayBegin)
                            .FirstOrDefault(t => t.监测时间 < dayBegin);
                        monitorMaster.日排放量 = 0;
                        if (dayMaster != null)
                        {
                            monitorMaster.日排放量 = dayMaster.时段量;
                        }
                    }

                    if (content.Contains("B01-Mon"))
                    {
                        monitorMaster.月排放量 = Parser.GetDoubleByKey("B01-Mon", content) ?? 0;
                    }
                    else
                    {
                        var monthBegin = new DateTime(datatime.Value.Year, datatime.Value.Month, 1, 0, 0, 0);
                        var monthEnd = monthBegin.AddMonths(1);
                        monthMaster = pCtx.主月数据
                            .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                            .Where(t => t.企业排口ID == letport.ID)
                            .Where(t => t.监测时间 >= monthBegin)
                            .FirstOrDefault(t => t.监测时间 < monthEnd);
                        monitorMaster.月排放量 = 0;
                        if (monthMaster != null)
                        {
                            monitorMaster.月排放量 = monthMaster.时段量;
                        }
                    }

                    var yearBegin = new DateTime(datatime.Value.Year, 1, 1, 0, 0, 0);
                    var yearEnd = yearBegin.AddYears(1);
                    var yearMaster = pCtx.主年数据
                        .Where(t => t.企业基本信息ID == letport.企业基本信息ID)
                        .Where(t => t.企业排口ID == letport.ID)
                        .Where(t => t.监测时间 >= yearBegin)
                        .FirstOrDefault(t => t.监测时间 < yearEnd);
                    monitorMaster.年排放量 = 0;
                    if (yearMaster != null)
                    {
                        monitorMaster.年排放量 = yearMaster.时段量;
                    }

                    var codes = Parser.GetPollutantCodes(content);
                    foreach (var code in codes)
                    {
                        Log.Info("code->" + code);
                        var contamCodeId = CommonInformation.GetContamCode(code) == null
                            ? 2
                            : CommonInformation.GetContamCode(code).ID;
                        if (!code.Contains("B01"))
                        {
                            var monitorDetail = monitorMaster.从实时监控.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (monitorDetail == null)
                            {
                                monitorDetail = new 从实时监控
                                {
                                    污染物编码ID = CommonInformation.GetContamCode(code).ID
                                };
                                monitorMaster.从实时监控.Add(monitorDetail);
                            }

                            monitorDetail.瞬时量 = Parser.GetDoubleByKey(code + "-Rtd", content) ?? 0;
                            //detailMonitor.小时排放量 = Parser.GetDoubleByKey(code + "-Cou", content) ?? 0;
                            if (content.Contains(code + "-Day"))
                            {
                                monitorDetail.日排放量 = Parser.GetDoubleByKey(code + "-Day", content) ?? 0;
                            }
                            else
                            {
                                var dayDetail = dayMaster?.从日数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                                if (dayDetail != null)
                                {
                                    monitorDetail.日排放量 = dayDetail.Cou;
                                }
                            }

                            if (content.Contains(code + "-Mon"))
                            {
                                monitorDetail.月排放量 = Parser.GetDoubleByKey(code + "-Mon", content) ?? 0;
                            }
                            else
                            {
                                var monthDetail = monthMaster?.从月数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                                if (monthDetail != null)
                                {
                                    monitorDetail.月排放量 = monthDetail.Cou;
                                }
                            }

                            Log.Info("->" + monitorDetail.瞬时量 + "->" + monitorDetail.小时排放量);
                            var detail = yearMaster?.从年数据.FirstOrDefault(t => t.污染物编码ID == contamCodeId);
                            if (detail != null)
                            {
                                monitorDetail.年排放量 = detail.Cou;
                            }
                        }
                    }
                    pCtx.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }
        }
    }
}
